import AppDataSource from "@/common/database";
import { Permission } from "@/models/Permission";
import { Role } from "@/models/Role";
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { z } from "zod";

const permissionRoute = new Hono();

permissionRoute.get("/list", async (c) => {
  let query = c.req.query();

  if (query.roleId) {
    let roleId = +query.roleId;

    let role = await AppDataSource.createQueryBuilder()
      .select("role")
      .from(Role, "role")
      .leftJoinAndSelect("role.permissions", "permission")
      .where("role.id = :roleId", { roleId })
      .getOne();

    let list = role?.permissions;

    return c.json({ message: "success", code: 200, data: { list } });
  } else {
    let [list, count] = await AppDataSource.createQueryBuilder()
      .select("permission")
      .from(Permission, "permission")
      .getManyAndCount();

    return c.json({ message: "success", code: 200, data: { list, count } });
  }
});

const addSchema = z.object({
  name: z.string(),
  path: z.string(),
});

const updateSchema = z.object({
  id: z.coerce.number(),
  name: z.string(),
  path: z.string(),
});

permissionRoute.post("/add", async (c) => {
  let body = await c.req.parseBody();
  let result = addSchema.safeParse(body);

  if (!result.success) {
    let message = result.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let permission = new Permission();
  permission.name = result.data.name;
  permission.path = result.data.path;

  await permission.save();

  return c.json({ message: "hello", code: 200, data: permission });
});

permissionRoute.post("/edit", async (c) => {
  let body = await c.req.parseBody();
  let result = updateSchema.safeParse(body);

  if (!result.success) {
    let message = result.error.issues
      .map((item) => item.path.join(",") + item.message)
      .join(",");
    throw new HTTPException(400, { message });
  }

  let permission = await Permission.findOneBy({ id: result.data.id });

  if (!permission) {
    throw new HTTPException(404, { message: "权限不存在" });
  }

  permission.name = result.data.name;
  permission.path = result.data.path;

  await permission.save();

  return c.json({ message: "hello", code: 200, data: permission });
});

export default permissionRoute;
